<template>
  <el-form ref="refForm" :model="formData" label-position="top">
    <el-form-item label="内容类型" prop="contentType">
      <el-select
        @change="(val) => handelChange(val, 'changeSelect')"
        v-model="formData.contentType"
        placeholder="请选择内容类型"
        style="width: 100%"
      >
        <el-option value="fixedValue" label="固定值"></el-option>
        <el-option value="variable" label="变量"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item
      v-if="formData.contentType === 'fixedValue'"
      label="内容"
      prop="content"
    >
      <el-input
        @change="handelChange"
        v-model="formData.content"
        :maxlength="128"
        style="width: 100%"
        placeholder="请输入内容"
      />
    </el-form-item>
    <el-form-item v-else label="显示值" prop="content">
      <LabelExpressionTree
        @change="handelChange"
        style="width: 100%"
        v-model="formData.content"
        :fields="fieldList"
      />
    </el-form-item>
  </el-form>
</template>
<script>
import { breadFirstTree } from "@/utils/util"
import LabelExpressionTree from "@/components/LabelExpressionTree"
import { getHmentitymodelListTree } from "@/apis/paas/HmEntityModelController.js"
export default {
  name: "QRCodeConfig",
  data() {
    return {
      formData: {},
      fieldList: [],
    }
  },
  props: {
    modelCode: {
      type: String,
      required: true,
    },
  },
  components: {
    LabelExpressionTree,
  },
  methods: {
    init(data) {
      this.formData = {}
      this.loadFields()
      this.$set(this.formData, "contentType", data.contentType)
      this.$set(this.formData, "content", data.content)
    },
    async loadFields() {
      if (!this.modelCode) return
      this.fieldList = await getHmentitymodelListTree({
        modelCode: this.modelCode,
      })
      breadFirstTree(
        this.fieldList,
        (node) => {
          node.label = node.name
          node.value = node.value || node.code
          node.showName = `${node.name}[${node.code}]`
          node.disabled = node.type === "SUB_TABLE"
          node.children &&
            node.children.forEach((child) => {
              child.value = `${node.value}.${child.code}`
            })
          return true
        },
        "children"
      )
    },
    handelChange(val, isChangeSelect) {
      if (isChangeSelect === "changeSelect") {
        this.$set(this.formData, "content", "")
      }
      this.$emit("changeData", {
        content: this.formData.content,
        contentType: this.formData.contentType,
        type: 2,
      })
    },
  },
}
</script>
